package com.edu.dk.security.impl;

import com.edu.dk.security.BasicWebContext;
import com.edu.dk.security.WebContext;
import com.edu.dk.security.exception.WebContextException;
import com.edu.dk.security.util.HumanReadableSize;

/**
 * 过滤header中的crlf，将status message用HTML entities转义，限制cookie的总大小。
 * 
 *
 */
public class BasicWebContextImpl extends AbstractWebContextWrapper implements BasicWebContext {
	private static final long serialVersionUID = -6400266221206803672L;

	private Object[] interceptors;

	private String maxCookieSize;

	public BasicWebContextImpl(WebContext wrappedContext) {
		super(wrappedContext);
	}

	public String getMaxCookieSize() {
		return maxCookieSize;
	}

	public void setMaxCookieSize(String maxSetCookieSize) {
		this.maxCookieSize = maxSetCookieSize;
	}

	public Object[] getResponseHeaderInterceptors() {
		return interceptors.clone();
	}

	public void commitHeaders() throws WebContextException {
		((BasicResponseImpl) getResponse()).commitHeaders();
	}

	public void prepareResponse() {
		((BasicResponseImpl) getResponse()).prepareResponse();
	}

	public void commitResponse() {
		((BasicResponseImpl) getResponse()).commitResponse();
	}

	private Object[] addDefaultInterceptors(Object[] interceptors) {
		ResponseHeaderSecurityFilter defaultInterceotor = new ResponseHeaderSecurityFilter();
		if (maxCookieSize != null) {
			defaultInterceotor.setMaxCookieSize(new HumanReadableSize(maxCookieSize));
		}
		if (interceptors == null || interceptors.length == 0) {
			return new Object[] { defaultInterceotor };
		}

		for (Object interceptor : interceptors) {
			if (interceptor instanceof ResponseHeaderSecurityFilter) {
				return interceptors;
			}
		}

		// appending response-header-security-filter
		Object[] newInterceptors = new Object[interceptors.length + 1];
		System.arraycopy(interceptors, 0, newInterceptors, 0, interceptors.length);
		newInterceptors[interceptors.length] = defaultInterceotor;

		return newInterceptors;
	}

	public void initContext(Object[] interceptors) {
		this.interceptors = addDefaultInterceptors(interceptors);
		setResponse(new BasicResponseImpl(this, getWrappedWebContext().getResponse(), this.interceptors));
	}
}
